package com.beiye.drivertransport.thematic.learning.examiantion;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CertificateCompletionBean;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.QRCodeUtil;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//通用结业证书
public class AdministratorcertificateActivity extends TwoBaseAty {

    TextView tv_back;

    TextView tv_save;

    WebView wb_post;

    ProgressBar pb_certificate;
    private String certUrl;

    @Override
    public int getLayoutId() {
        return R.layout.activity_administratorcertificate;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_back) {
            finish();
        } else if (id == R.id.tv_save) {//截图
            Bitmap bitmap = captureScreenforRecord();
            if (bitmap != null) {
                //保存图片
                saveImageToGallery(this, bitmap);
                showToast("保存相册成功");

            }
        }

    }

    @Override
    public void initData() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_save = (TextView) findViewById(R.id.tv_save);
        wb_post = (WebView) findViewById(R.id.wb_post);
        pb_certificate = (ProgressBar) findViewById(R.id.pb_certificate);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#FFFFFF"));
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        certUrl = bundle.getString("certUrl");
        LogUtils.e("测试", "requestData: "+certUrl );
        WebSettings settings = wb_post.getSettings();
        settings.setSavePassword(false);
        settings.setSaveFormData(false);
        wb_post.removeJavascriptInterface("accessibility");
        wb_post.removeJavascriptInterface("accessibilityTraversal");
        settings.setAllowFileAccessFromFileURLs(false);
        // 允许使用脚本语言
        settings.setJavaScriptEnabled(true);
        // 支持缩放
        settings.setSupportZoom(true);
        //Android 5.0中使用webView 加载网页不显示图片问题
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        wb_post.loadUrl(certUrl);
        // 在当前应用加载网页(直接加载网页不经过浏览器）
        wb_post.setWebViewClient(new WebViewClient() {
            @Override // 开始加载网页时触发
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                pb_certificate.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override // 网页加载完成之后触发
            public void onPageFinished(WebView view, String url) {
                pb_certificate.setVisibility(View.INVISIBLE);
                super.onPageFinished(view, url);

            }
        });

        // 显示进度
        wb_post.setWebChromeClient(new WebChromeClient() {
            @Override // 加载网页进度改变时触发
            public void onProgressChanged(WebView view, int newProgress) {
                pb_certificate.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });

    }

    //截图
    private Bitmap captureScreenforRecord() {

        wb_post.measure(View.MeasureSpec.makeMeasureSpec(
                View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        wb_post.layout(0, 0, wb_post.getMeasuredWidth(),
                wb_post.getMeasuredHeight());
        wb_post.setDrawingCacheEnabled(true);
        wb_post.buildDrawingCache();

        Bitmap bm = Bitmap.createBitmap(wb_post.getMeasuredWidth(),
                wb_post.getMeasuredHeight(), Bitmap.Config.RGB_565);

        Canvas bigcanvas = new Canvas(bm);
        Paint paint = new Paint();
        int iHeight = bm.getHeight();
        bigcanvas.drawBitmap(bm, 0, iHeight, paint);
        wb_post.draw(bigcanvas);
        return bm;
    }

    /**
     * 保存图片到手机上，并通知图库更新
     *
     * @param context
     * @param bmp
     * @return
     */
    public String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Pictures/Signname/");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        String path = Environment.getExternalStorageDirectory() + "/Pictures/Signname/"
                + fileName;
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        return Environment.getExternalStorageDirectory() + "/Pictures/Signname/" + fileName;
    }
}
